/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.impl;

import java.net.URI;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.iosgi.IsolatedFramework;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.util.tracker.ServiceTracker;

/**
 * @author Sven Schulz
 */
public class Utils {

	public static IsolatedFramework waitForIsolatedFramework(
			BundleContext context, URI envId, long timeout, TimeUnit unit)
			throws InterruptedException, TimeoutException {
		Filter f = null;
		try {
			f = FrameworkUtil.createFilter("(& (objectClass="
					+ IsolatedFramework.class.getName() + ") (environment.id="
					+ envId + "))");
		} catch (InvalidSyntaxException ise) {
			assert false;
		}
		ServiceTracker t = new ServiceTracker(context, f, null);
		t.open();
		Object obj = t.waitForService(TimeUnit.MILLISECONDS.convert(timeout,
				unit));
		if (obj == null) {
			throw new TimeoutException();
		}
		return (IsolatedFramework) obj;
	}

}